package com.cht.commonUtil.svn;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.enums.ReqStatus;
import com.cht.commonUtil.structure.I1S2;
import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class GetRelatedReqs extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/json");
		
		boolean isReqDescNeed = "t".equalsIgnoreCase( request.getParameter("isReqDescNeed") );
		int localSystemId = Widgets.getParNumberFromRequest( request.getParameter("localSystemId") );
		String subsysId = request.getParameter("subsysId");
		String svnUrl = request.getParameter("svnUrl");
		String svnId = request.getParameter("svnId");
		String svnPwd = request.getParameter("svnPwd");
		long reversion = Long.parseLong( request.getParameter("reversion") );
		String target = Widgets.getSVNcomment(svnUrl, svnId, svnPwd, reversion);
		
		String startTopToken = "{";
		String endTopToken = "}";
		String startMidToken = "[";
		String endMidToken = "]";
		
		List<I1S2> reses = new ArrayList<I1S2>();
		List<I1S2> finalRes = new ArrayList<I1S2>();	//最後要回傳給使用者的陣列，它會過濾掉不符合需求規定的
		
		if( target.contains(startTopToken) && target.contains(endTopToken) ) {
			int start = target.indexOf(startTopToken);
			int end = target.lastIndexOf(endTopToken);
			String tmp = target.substring(start+1,end).trim();
			int sNum = Widgets.numberOfKeywords(tmp,startMidToken);
			int eNum = Widgets.numberOfKeywords(tmp,endMidToken);
			if( sNum == eNum && sNum== 1) {
				
				if( target.contains(",") ) {
					int sTokenIdx = tmp.indexOf(startMidToken);
					int eTokenIdx = tmp.lastIndexOf(endMidToken);
					tmp = tmp.substring(sTokenIdx+1, eTokenIdx);
					String[] arr = tmp.split(",");
					for(int i=0;i<arr.length;i++) {
						I1S2 s2 = new I1S2();
						s2.setS1(arr[i].trim());
						s2.setS2("");
						reses.add(s2);
					}
				} else {
					int sTokenIdx = tmp.indexOf(startMidToken);
					int eTokenIdx = tmp.lastIndexOf(endMidToken);
					
					I1S2 s2 = new I1S2();
					if( eTokenIdx+1 == end ) {
						s2.setS1(tmp.trim());
						s2.setS2("");
					} else {
						String cmd = tmp.substring(eTokenIdx+1, tmp.length()).trim();
						sTokenIdx = tmp.indexOf(startMidToken);
						eTokenIdx = tmp.lastIndexOf(endMidToken);
						tmp = tmp.substring(sTokenIdx+1, eTokenIdx);
						s2.setS1(tmp.trim());
						s2.setS2(cmd);
					}
					reses.add(s2);
				}
			} else if( sNum == eNum && sNum > 1) {
				 List<Integer> sList = Widgets.getIdxArr(tmp,startMidToken);
				 List<Integer> eList = Widgets.getIdxArr(tmp,endMidToken);
				 
				 for(int i=0;i<sList.size();i++) {
					 I1S2 s2 = new I1S2();
					 s2.setS1( tmp.substring(sList.get(i)+1,eList.get(i)).trim() );
					 if( i+1 !=sList.size()  ) {
						 s2.setS2( tmp.substring(eList.get(i)+1, sList.get(i+1)).trim()  );
					 } else {
						 s2.setS2( tmp.substring(eList.get(i)+1, tmp.length() ).trim()  );
					 }
					 reses.add(s2);
				 }
			} else if( sNum != eNum) {
				System.out.println("語法有誤，"+startMidToken+"與"+endMidToken+"數量應一致");
			}
			
			if( sNum == eNum ) {
				if( isReqDescNeed ) {
					for(int i=0;i < reses.size();i++) {
						if( !"".equalsIgnoreCase( reses.get(i).getS2().trim() ) ) {
							finalRes.add(reses.remove(i));
						}
					}	
				} else { finalRes = reses; }
			}
		} else {
			System.out.println("使用者沒提.");
		}


		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = Widgets.getConn();
			
			
			for(int i=0;i<finalRes.size();i++) {
				String sql = "SELECT COUNT(*) FROM reqs WHERE reqSID=?";
				String reqSID = finalRes.get(i).getS1();
				ps = conn.prepareStatement(sql);
				ps.setString(1, reqSID);
				rs = ps.executeQuery();
				rs.next();
				if( rs.getInt(1) == 0 ) {
					if ( rs !=null ) {rs.close();}
					if ( ps !=null ) {ps.close();}
					sql = "INSERT INTO reqs (reqSID,reqDesc,subsysId,isClosed,sysSN,status,cDT,sysLog) VALUES (?,?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(sql, new String[]{"reqId"} );
					ps.setString(1, reqSID );
					ps.setString(2, finalRes.get(i).getS2() );
					ps.setString(3, subsysId);
					ps.setString(4, "f" );
					ps.setInt(5, localSystemId);
					ps.setInt(6, ReqStatus.OPEN.getValue());
					ps.setTimestamp(7, Widgets.cDT() );
					ps.setString(8, "From Commit:"+reversion);
					ps.execute();
					rs = ps.getGeneratedKeys();
					rs.next();
					finalRes.get(i).setI1(rs.getInt(1));
				} else {
					System.out.println("已存在，不新增");
				}
			}
		} catch (Exception e) {
			Widgets.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch(Exception e) { e.printStackTrace(); }
		}
		
		response.getWriter().write( new Gson().toJson(finalRes) );
	}
}
